<?php
/**
 * Created by PhpStorm.
 * User: chenxiaomo
 * Date: 9/22/22
 * Time: 3:52 PM
 */

namespace app\core\middleware;

use think\Request;
use think\Response;

/**
 * 全局跨域中间件
 * Class AllowCrossDomain
 * @package app\core\middleware
 */
class AllowCrossDomain
{

    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
    ];

    public function handle(Request $request, \Closure $next, ?array $header = [])
    {

        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;

        $httpOrigin = $request->header('origin');

        if ($httpOrigin && strpos(config('cookie.domain'), $httpOrigin)) {
            $header['Access-Control-Allow-Origin'] = $httpOrigin;
        } else {
            $header['Access-Control-Allow-Origin'] = '*';
        }

        $header['Access-Control-Allow-Headers'] = "*";

        foreach ($header as $k => $v) {
            header($k . ": " . $v);
        }

        if ($request->method(true) == 'OPTIONS') {
            return Response::create()->code(204)->header($header);
        }

        return $next($request);
    }
}